package com.hansming.bss.modules.sfc.wxpay;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hansming.bss.common.utils.PropertiesLoader;
import com.hansming.bss.common.web.BaseController;
import com.hansming.bss.modules.sfc.entity.Customer;
import com.hansming.bss.modules.sfc.entity.CustomerScoreLog;
import com.hansming.bss.modules.sfc.entity.Order;
import com.hansming.bss.modules.sfc.service.CustomerScoreLogService;
import com.hansming.bss.modules.sfc.service.CustomerService;
import com.hansming.bss.modules.sfc.service.OrderService;
import com.hansming.bss.modules.sfc.util.CarTimeHelp;
import com.hansming.bss.modules.sfc.util.PhoneMsgUtil;
import com.hansming.bss.modules.sfc.util.SendMailUtil;




@Controller
@RequestMapping(value="/wx") 
public class WxNotifypc extends BaseController{

	@Autowired
	private OrderService orderService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private CustomerScoreLogService customerscorelogService;
	
	
@RequestMapping(value="/wxNotifypc") 
@ResponseBody
public void wxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{  
	System.out.println("杰女士你好呀");
    BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));  
    String line = null;  
    StringBuilder sb = new StringBuilder();  
    while((line = br.readLine()) != null){  
        sb.append(line);  
    }  
    //sb为微信返回的xml  
    String notityXml = sb.toString();  
    String resXml = "";  
    System.out.println("接收到的报文：" + notityXml);  
  
    Map map = PayUtils.doXMLParse(notityXml);
    
    
    
      
    String returnCode = (String) map.get("return_code");  
    System.out.println("回调返回code------>"+returnCode);
    System.out.println("------>执行1<-------");
    if("SUCCESS".equals(returnCode)){  
    	System.out.println("------>执行2<-------");	
    	System.out.println("结果"+PayUtils.verify(PayUtils.createLinkString(map), (String)map.get("sign"), WxPayConfig.key, "utf-8"));
        //验证签名是否正确  
    	if(PayUtils.notify((String)map.get("sign"), map)){
        
            /**此处添加自己的业务逻辑代码start**/
        	orderService.updatetextbywxnum((String)map.get("out_trade_no"));
            System.out.println("进了回调>>>>>>wxnum:"+(String)map.get("out_trade_no"));
           Order order = orderService.selectorederbywxnum((String)map.get("out_trade_no"));
           if(!"".equals(order.getPhone()) && !"".equals(order.getNum())){
        	   PhoneMsgUtil.sendSingleSms(order.getPhone(), order.getNum());
        	 //发送邮件给运营人员
        	   PropertiesLoader config = new PropertiesLoader("config.properties");
       		String yunyingemail = config.getProperty("yunyingemail");
       		SimpleDateFormat  sdf =   new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss"); 
       		try {
    		
    			String emailtile = "小程序订单成功支付";
    			Date now = new Date();
    			String content = "<p>时间："+sdf.format(now)+"</p>"+
    										"<p>订单编号："+order.getNum()+"</p>"+
    										"<p>商品名称："+order.getProductname()+"</p>"+
    										"<p>总价为："+order.getPrice()+"元</p>";
    										
    			SendMailUtil.Sendmail(yunyingemail,emailtile , content);
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			System.out.println("发送邮件失败");
    		}
       		//支付完成增加积分
       		Customer user = customerService.get(order.getCustomer().getId());
       		System.out.println("支付前积分："+user.getScore());
       		user.setScore(user.getScore()+(order.getPrice().multiply(new BigDecimal("0.2"))).intValue());
       		System.out.println("支付获得积分："+(order.getPrice().multiply(new BigDecimal("0.2"))).intValue()+",支付后积分："+user.getScore());
       		customerService.updatescore(user);
       		//记录积分的增加
       		Date now = new Date();
       		CustomerScoreLog csl = new CustomerScoreLog();
       		csl.setDatetime(sdf.format(now));
       		csl.setScore((order.getPrice().multiply(new BigDecimal("0.2"))).intValue());
			csl.setDetail("订购"+order.getProductname());
			csl.setType("1");
			csl.setCustomer(user);
			customerscorelogService.save(csl);
			
			
			
			System.out.println("支付成功");
           }
            /**此处添加自己的业务逻辑代码end**/  
            //通知微信服务器已经支付成功  
            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
            + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
        }  
    }else{  
    	System.out.println("------>执行4<-------");
        resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
        + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
    }  
    System.out.println(resXml);  
    System.out.println("微信支付回调数据结束");  


    BufferedOutputStream out = new BufferedOutputStream(  
            response.getOutputStream());  
    out.write(resXml.getBytes());  
    out.flush();  
    out.close();  
}  

}
